const COMMON_URL = "common/request";
var channelName = "";
var peerNums = 0;
var blockNums = 0;
var txNums = 0;
var chaincodeNums = 1;
var chainInfo = "";
var blockInfo = [];
var peerInfo = [];
// var blockInfo = [];
var currentblockNumber = 0;
$(document).ready(function () {
    listChannel();
    listenChannel();
    infoBlock();
    $("#blockList").bootstrapTable({
        height: "400",
        iconSize: "outline",
        rowStyle: function (row, index) {
            var style = 'info';
            if (index % 6 == 1) {
                style = "primary"
            } else if (index % 6 == 2) {
                style = "active"
            } else if (index % 6 == 3) {
                style = "warning"
            } else if (index % 6 == 4) {
                style = "danger"
            } else if (index % 6 == 5) {
                style = "success"
            }
            return {classes: style}
        },
        columns: [
            {
                title: "block编号",
                field: "blockNum",
                align: "center",
                formatter: function (value) {
                    return "<i class='label label-primary'># " + value + "</i>";
                }
            }, {
                title: "交易数量",
                field: "txCount",
                align: "center"
            }]
    });
});
function initBlockTable() {
    var queryParams = {"channelName": "channel1"};
    $("#blockList").bootstrapTable({
        // ajax: function (request) {
        //     var url = "chain/block/base/list";
        //     var para = {"channelName": "channel1"};
        //     ajax("block/list", getArgs(url, para), function (data) {
        //         // if (data.code == 1000) {
        //         //     var msg = data.data.mBlocks;
        //
        //         // }
        //             request.success({
        //                 row: data
        //             });
        //         $('#blockList').bootstrapTable('load', data);
        //     });
        // },
        url: "block/list",
        // data: JSON.stringify({"channelName": "channel1"}),
        dataType: "json",
        queryParams: queryParams, //参数
        method: "post",
        height: "800",
        iconSize: "outline",
        // search: true,
        // showRefresh: true,
        rowStyle: function (row, index) {
            var style = 'info';
            if (index % 6 == 1) {
                style = "primary"
            } else if (index % 6 == 2) {
                style = "active"
            } else if (index % 6 == 3) {
                style = "warning"
            } else if (index % 6 == 4) {
                style = "danger"
            } else if (index % 6 == 5) {
                style = "success"
            }
            return {classes: style}
        },
        // pagination: true,
        // showColumns: !0,
        // singleSeclect: true,
        columns: [
            {
                title: "block编号",
                field: "blockNum",
                align: "center",
                formatter: function (value) {
                    // return "<i class='label label-primary' onclick='"+queryBlock(value)+"'># "+value+"</i>";
                    return "<i class='label label-primary'># " + value + "</i>";
                }
            }, {
                title: "交易数量",
                field: "txCount",
                align: "center"
            }
            // {
            //     title: "路径",
            //     field: "path",
            //     align: "center",
            //     formatter: function (value) {
            //         if (value == 1) {
            //             return "<span type='text' class='btn btn-primary btn-sm'>已启用</span>";
            //         } else {
            //             return "<span type='text' class='btn btn-danger btn-sm'>已禁用</span>";
            //         }
            //     }
            // }
        ]
    });
}
function initPeerTable() {
    $("#peerListTable").bootstrapTable({
        url: "peer/list/channelName",
        data: postData,
        method: "post",
        height: "300",
        iconSize: "outline",
        // search: true,
        // showRefresh: true,
        // rowStyle: "success",
        pagination: true,
        // showColumns: !0,
        // singleSeclect: true,
        columns: [
            // {radio: true},
            {
                title: "peerId",
                field: "peerId",
                align: "center"
            }, {
                title: "节点名称",
                field: "peerName",
                align: "center"
            }, {
                title: "节点地址",
                field: "hostAddress",
                align: "center"
            }, {
                title: "端口",
                field: "port",
                align: "center"
            }, {
                title: "事件端口",
                field: "eventPort",
                align: "center"
            }, {
                title: "TLS状态",
                field: "tlsFlag",
                align: "center"
            }
            // {
            //     title: "路径",
            //     field: "path",
            //     align: "center",
            //     formatter: function (value) {
            //         if (value == 1) {
            //             return "<span type='text' class='btn btn-primary btn-sm'>已启用</span>";
            //         } else {
            //             return "<span type='text' class='btn btn-danger btn-sm'>已禁用</span>";
            //         }
            //     }
            // }
        ]
        // icons: {
        //     refresh: "glyphicon-repeat",
        //     toggle: "glyphicon-list-alt",
        //     columns: "glyphicon-list"
        // }
    });
}
function infoBlock() {
    $('#blockList').on('click-row.bs.table', function (e, row, element) {
        queryBlock(row.blockNum);
    });
}
function queryBlock(blockNum) {
    currentblockNumber = blockNum;
    setBlockInfo();
}
function setTable() {
    $('#blockList').bootstrapTable('destroy');
    initBlockTable();
}
function loadPeerList() {
    $('#peerListTable').bootstrapTable('load', peerInfo);
}
function infoChain() {
    $("#chain").modal('show');
}
function loadBlockList(blockInfos) {
    $('#blockList').bootstrapTable('load', blockInfos);
}
function listChannel() {
    $.ajax(
        {
            url: "/channel/list",
            data: {"data": "channel"},
            type: "post",
            // async: false,
            dataType: "json",
            beforeSend: function () {
            },
            success: function (data) {
                if (data.code == 1000) {
                    // location.reload();
                    setChannel(data.data);
                } else {
                    swal({
                        title: "查询channel失败！",
                        type: "error"
                    });
                }
            }
            ,
            error: function () {
                swal({
                    title: "请求出错！",
                    type: "error"
                });
            }
        })
    ;
}
function setChannel(channels) {
    var deviceStr = "";
    for (var i = 0; i < channels.length; i++) {
        // var style = "<option data-content='<span class=" + '"label label-info"' + ">" + channels[i] + "</span>" + "'> " + channels[i] + "</option>";
        var style = "<option value='" + channels[i] + "'> " + channels[i] + "</option>";
        // deviceStr += "<option  data-icon='glyphicon glyphicon-heart' value='" + channels[i] + "'> " + channels[i] + "</option>";
        deviceStr += style;
    }
    $("#channelName").html("");
    $('#channelName').append(deviceStr);
    $('#channelName').selectpicker('refresh');
}
function listenChannel() {
    $('#channelName').on('changed.bs.select', function (e) {
        channelName = $('#channelName').val();
        refreshPage();
    });
}
function getblockDetail() {
    var blockDetail = JSON.stringify(blockInfo[currentblockNumber], null, "\t");
    var txDetail = JSON.stringify(blockInfo[currentblockNumber].mfTransactions, null, "\t");
    $('#blockDetail').val(blockDetail);
    $('#txDetail').val(txDetail);
    $("#blockInfo").modal('show');
}
function getBlockInfo(channelName) {
    var url = "chain/block/list";
    var para = {"channelName": channelName};
    ajax(COMMON_URL, getArgs(url, para), function (data) {
        chainInfo = data.data;
        var mBlocks = data.data.mBlocks;
        var lastBlockNumber = data.data.height - 1;
        loadBlockList(mBlocks);
        currentblockNumber = lastBlockNumber;
        $('#chaincResult').val(JSON.stringify(data.data, null, "\t"));
        blockNums = data.data.height;
        var mfTransactionsBuff = "";
        for (var i = 0; i < mBlocks.length; i++) {
            var bn = mBlocks[i].blockNum;
            blockInfo[bn] = mBlocks[i];
            if (mBlocks[i].blockNum == lastBlockNumber) {
                var mfTransactions = mBlocks[i].mfTransactions;
                for (var j = 0; j < mfTransactions.length; j++) {
                    mfTransactionsBuff += mfTransactions[j].txId;
                    if (j != mfTransactions.length - 1) {
                        mfTransactionsBuff += ",";
                    }
                }
            }
            txNums += mBlocks[i].mfTransactions.length;
        }
        $("#transactions").html(mfTransactionsBuff);
        setHeadInfo();
        setBlockInfo();
    });
}
function setBlockInfo() {
    $("#currentBlockNum").html("# " + currentblockNumber);
    $("#currentBlockNumber").html("# " + currentblockNumber);
    $("#currentBlockHash").html(blockInfo[currentblockNumber].calculateHash);
    $("#preBlockHash").html(blockInfo[currentblockNumber].preHash);
}
function initParms() {
    peerNums = 0;
    blockNums = 0;
    txNums = 0;
    chaincodeNums = 1;
    chainInfo = "";
    blockInfo = [];
}
function getArgs(url, args) {
    var para = {"url": url, "args": args};
    return para;
}
function getPeerListByChannelName(channelName) {
    // var url = "peer/list/channelName";
    // var para = {"channelName": channelName};
    // ajax(COMMON_URL, getArgs(url, para), function (data) {
    //     if(data.code==1000){
    //         peerInfo = data.data;
    //         loadPeerList();
    //         // alert(data.data.length);
    //     }
    var postData = {"channelName": channelName};
    ajax("block/list", postData, function (data) {
        if (data.code == 1000) {
            peerNums = data.data.length;
            peerInfo = data.data;
            loadPeerList();
        }
    });
}
function refreshPage() {
    if (channelName != "") {
        initParms();
        getPeerListByChannelName(channelName);
        getBlockInfo(channelName);

        // setTable();
        // var url = "rest/test";
        // var postData = {"channelName": "channel8"};
        // ajax(url, postData, function (data) {
        //     if (data.code == 1000) {
        //         alert(data.data);
        //     }
        // });
    } else {
        swal({
            title: "请先选择channel",
            type: "warning"
        });
    }
}
function setHeadInfo() {
    $('#peerNums').html(peerNums);
    $('#blockNums').html(blockNums);
    $('#txNums').html(txNums);
    $('#chaincodeNums').html(chaincodeNums);
}
function ajax(url, reqData, Func) {
    $.ajax(
        {
            url: url,
            data: reqData,
            type: "post",
            // async: false,
            dataType: "json",
            // contentType: "application/json;charset=UTF-8",
            beforeSend: function () {
            },
            success: function (data) {
                Func(data);
            },
            error: function () {
                swal({
                    title: "请求出错！",
                    type: "error"
                });
            }
        });
}
